package com.alan.swagger2.mail;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;

/**
 * @Auther: Alan liu
 * @Date: 2018/9/29 15:44
 * @Description: MailSendService
 */
@Service
public class MailService {


    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private UserMailProperties userMailProperties;

    public void sendSimpleMail(String subject, String text) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(userMailProperties.getFrom());
        mailMessage.setTo(userMailProperties.getTo());

        mailMessage.setSubject(subject);
        mailMessage.setText(text);

        javaMailSender.send(mailMessage);
    }

    public void sendHtmlMail(String subject, String text, Map<String, String> attachmentMap) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        //是否发送的邮件是富文本（附件，图片，html等）
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

        messageHelper.setFrom(userMailProperties.getFrom());
        messageHelper.setTo(userMailProperties.getTo());

        messageHelper.setSubject(subject);
        messageHelper.setText(text, true);//重点，默认为false，显示原始html代码，无效果

        if(attachmentMap != null){
            attachmentMap.entrySet().stream().forEach(entrySet -> {
                try {
                    //本地附件
                    File file = new File(entrySet.getValue());
                    if(file.exists()){
                        messageHelper.addAttachment(entrySet.getKey(), new FileSystemResource(file));
                    }
                    //网络附件
//                    URL url = new URL( entrySet.getValue() );
//                    DataHandler dataHandler = new DataHandler( url );
//                    messageHelper.addAttachment( entrySet.getKey(), dataHandler.getDataSource() );
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            });
        }

        javaMailSender.send(mimeMessage);
    }

    public void sendTemplateMail(String subject, Map<String, Object> params) throws MessagingException, IOException, TemplateException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setFrom(userMailProperties.getFrom());
        helper.setTo(userMailProperties.getTo());

        Configuration configuration = new Configuration(Configuration.VERSION_2_3_26);
        configuration.setClassForTemplateLoading(this.getClass(), "/templates");

        String html = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("mail.ftl"), params);

        helper.setSubject(subject);
        helper.setText(html, true);//重点，默认为false，显示原始html代码，无效果

        javaMailSender.send(mimeMessage);
    }

    /**
     * 获取用户的发件箱文件夹
     * @param message 信息
     * @param store 存储
     * @return
     * @throws IOException
     * @throws MessagingException
     */
    private Folder getSentMailFolder(Message message, Store store)
            throws IOException, MessagingException {
        // 准备连接服务器的会话信息
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", "imap.exmail.qq.com");
        props.setProperty("mail.imap.port", "993");

        /** QQ邮箱需要建立ssl连接 */
        props.setProperty("mail.imap.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.imap.socketFactory.fallback", "false");
        props.setProperty("mail.imap.starttls.enable", "true");
        props.setProperty("mail.imap.socketFactory.port", "993");

        // 创建Session实例对象
        Session session = Session.getInstance(props);
        URLName urln = new URLName("imap", "imap.exmail.qq.com", 993, null,
                "liuwei@iyunbao.com", "Xyz123456");
        // 创建IMAP协议的Store对象
        store = session.getStore(urln);
        store.connect();
        // 获得发件箱
        Folder folder = store.getFolder("Sent Messages");
        // 以读写模式打开发件箱
        folder.open(Folder.READ_WRITE);
        return folder;
    }

    /**
     * 保存邮件到发件箱
     * @param message
     *            邮件信息
     */
    private void saveEmailToSentMailFolder(Message message) {
        Store store = null;
        Folder sentFolder = null;
        try {
            sentFolder = getSentMailFolder(message, store);
            // 设置已读标志
            message.setFlag(Flags.Flag.SEEN, true);
            sentFolder.appendMessages(new Message[] { message });
            System.out.println("已保存到发件箱...");
        } catch (Exception e) {
            //当在邮箱设置里设置了"保存已发送邮件到服务器时(仅对smtp协议有效)"会报 "A3 NO Mail has saved by smtp!"
            if(!"A3 NO Mail has saved by smtp!".equals(e.getMessage())){
//                log.error("保存邮件到发件箱异常: {}",e);
            }
        } finally {
            // 判断发件文件夹是否打开如果打开则将其关闭
            if (sentFolder != null && sentFolder.isOpen()) {
                try {
                    sentFolder.close(true);
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
            // 判断邮箱存储是否打开如果打开则将其关闭
            if (store != null && store.isConnected()) {
                try {
                    store.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

